<template>
	<view class="container">
		<!-- 标题栏 -->
		<view class="header">
			<text class="title">火灾烟雾检测结果</text>
			<view class="header-right">
				<text class="temp" v-if="temperature !== null">当前温度: {{ temperature }}℃</text>
				<uni-icons type="refresh" size="24" color="#fff" @click="fetchAllData" class="refresh-btn"></uni-icons>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<uni-load-more status="loading"></uni-load-more>
		</view>

		<!-- 错误提示 -->
		<view v-if="error" class="error">
			<text>{{ error }}</text>
			<button @click="fetchAllData" type="primary" size="mini">重试</button>
		</view>

		<!-- 图片列表 -->
		<scroll-view v-if="!loading && !error" scroll-y class="scroll-view" refresher-enabled
			@refresherrefresh="onRefresh">
			<view class="grid">
				<view v-for="(item, index) in detections" :key="index" class="card"
					@click="previewImage(item.url, index)">
					<image :src="item.url" mode="aspectFill" class="image" lazy-load></image>
					<view class="info">
						<text class="filename">{{ item.filename }}</text>
						<text class="size">{{ formatSize(item.size) }}</text>
						<text class="time">{{ formatTime(item.last_modified) }}</text>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="detections.length === 0" class="empty">
				<uni-icons type="image" size="50" color="#999"></uni-icons>
				<text class="empty-text">暂无检测数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				detections: [],
				temperature: null,
				loading: false,
				error: null,
				apiUrl: 'http://127.0.0.1:5000/api/detections',
				tempApiUrl: 'http://192.168.145.3/api/v1/temperature'
			}
		},
		onLoad() {
			this.fetchAllData()
		},
		methods: {
			// 获取所有数据（温度和检测结果）
			async fetchAllData() {
				this.loading = true
				this.error = null

				try {
					// 并行获取温度和检测结果
					await Promise.all([
						this.fetchTemperature(),
						this.fetchDetections()
					])
				} catch (err) {
					console.error('获取数据失败:', err)
					this.error = err.message || '获取数据失败'
				} finally {
					this.loading = false
				}
			},

			// 获取温度数据
			async fetchTemperature() {
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: this.tempApiUrl,
							method: 'GET',
							timeout: 5000,
							success: resolve,
							fail: reject
						})
					})

					// 处理温度API响应
					const responseData = res.data || res[1]?.data
					const statusCode = res.statusCode || res[1]?.statusCode

					if (statusCode === 200 && responseData) {
						// 假设API返回格式为: { temperature: 25.5 }
						this.temperature = responseData.temperature?.toFixed(1) || '--'
					} else {
						throw new Error('获取温度数据失败')
					}
				} catch (err) {
					console.error('获取温度失败:', err)
					this.temperature = '--'
					// 不阻断主流程，仅温度获取失败不影响整体
				}
			},

			// 获取检测结果
			async fetchDetections() {
				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: this.apiUrl,
							method: 'GET',
							timeout: 10000,
							success: resolve,
							fail: reject
						})
					})

					// 处理检测结果API响应
					const responseData = res.data || res[1]?.data
					const statusCode = res.statusCode || res[1]?.statusCode

					if (!statusCode) {
						throw new Error('无效的API响应结构')
					}

					if (statusCode !== 200) {
						throw new Error(`请求失败: ${statusCode}`)
					}

					if (!responseData?.detections) {
						throw new Error("返回数据缺少detections字段")
					}

					this.detections = responseData.detections.map(item => ({
						...item,
						url: this.ensureHttps(item.url)
					}))

				} catch (err) {
					console.error('获取检测结果失败:', err)
					throw err // 向上抛出错误
				}
			},

			ensureHttps(url) {
				return url ? url.replace('http://', 'https://') : ''
			},

			onRefresh() {
				this.fetchAllData().finally(() => {
					uni.stopPullDownRefresh()
				})
			},

			formatTime(timestamp) {
				if (!timestamp) return ''
				try {
					const date = new Date(timestamp)
					return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
				} catch {
					return timestamp
				}
			},

			formatSize(bytes) {
				if (!bytes) return ''
				const size = parseInt(bytes)
				if (isNaN(size)) return ''
				if (size < 1024) return `${size} B`
				if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
				return `${(size / (1024 * 1024)).toFixed(1)} MB`
			},

			previewImage(url, index) {
				uni.previewImage({
					current: index,
					urls: this.detections.map(item => item.url),
					indicator: "number"
				})
			}
		}
	}
</script>

<style>
	/* 基础样式 */
	page {
		background-color: #f5f5f5;
		height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 0;
	}

	/* 标题栏 */
	.header {
		background-color: #e74c3c;
		color: white;
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 0;
		z-index: 999;
	}

	.header-right {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.temp {
		font-size: 12px;
		color: rgba(255, 255, 255, 0.9);
	}

	.title {
		font-size: 18px;
		font-weight: bold;
	}

	.refresh-btn {
		padding: 5px;
	}

	/* 加载状态 */
	.loading {
		padding: 20px;
		display: flex;
		justify-content: center;
	}

	/* 错误提示 */
	.error {
		padding: 20px;
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #e74c3c;
	}

	/* 滚动区域 */
	.scroll-view {
		height: calc(100vh - 50px);
		padding: 10px;
		box-sizing: border-box;
	}

	/* 网格布局 */
	.grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
	}

	/* 卡片样式 */
	.card {
		background: white;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		transition: transform 0.2s;
	}

	.card:active {
		transform: scale(0.98);
	}

	.image {
		width: 100%;
		height: 150px;
		background-color: #eee;
	}

	.info {
		padding: 8px;
	}

	.filename {
		font-size: 12px;
		color: #333;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		overflow: hidden;
		font-weight: bold;
	}

	.size {
		font-size: 10px;
		color: #666;
		margin-top: 2px;
		display: block;
	}

	.time {
		font-size: 10px;
		color: #999;
		margin-top: 2px;
		display: block;
	}

	/* 空状态 */
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 300px;
		color: #999;
	}

	.empty-text {
		margin-top: 10px;
		font-size: 14px;
	}
</style>